package org.deng.vertx.springboot.web.controller;

import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;
import org.deng.vertx.springboot.entity.SysUser;
import org.deng.vertx.springboot.msg.MsgAddress;
import org.deng.vertx.springboot.pojo.PageBo;
import org.deng.vertx.springboot.pojo.ResData;
import org.deng.vertx.springboot.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 邓力宾
 * @date 2022/12/29 15:58
 * @desc
 */
@Component
@Slf4j
public class SysUserController extends BaseController{
    private ISysUserService sysUserService;

    @Autowired
    public void setSysUserService(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @Override
    public void configRouter(Router router) {
        router.route("/sysUser/get/:id").method(HttpMethod.GET).blockingHandler(this::get);
        router.route("/sysUser/getById").method(HttpMethod.GET).handler(this::getById);
        router.route("/sysUser/getPage").method(HttpMethod.GET).handler(this::getPage);
    }

    /**
     * 使用消息总线
     * @param ctx
     */
    private void getById(RoutingContext ctx) {
        String id = null;
        List<String> ids = ctx.queryParam("id");
        if(ids !=null && !ids.isEmpty()){
            id = ids.get(0);
        }else {
            writeJSON(ctx, ResData.error("id不能为空"));
            return;
        }
        //发送消息
        vertx.eventBus().request(MsgAddress.userServiceGetById, id , reply -> {
            writeJSON(ctx, ResData.okData(reply.result().body()));
        });
    }

    /**
     * 根据id获取
     * @param ctx
     */
    private void get(RoutingContext ctx) {
        String id = ctx.pathParam("id");
        SysUser sysUser = sysUserService.getById(id);
        writeJSON(ctx, ResData.okData(sysUser));
    }

    private void getPage(RoutingContext ctx){
        String page = getParam(ctx, "page");
        String size  = getParam(ctx, "size");
        vertx.eventBus().request(MsgAddress.userServiceGetPage,
                new PageBo(Integer.parseInt(page), Integer.parseInt(size)),
                reply->{
            writeJSON(ctx, reply.result().body());
        });

    }
}
